<?php
	// Check crossing acess
	if (!defined('RIGHT_ACCESS') || !defined('ROOT_FOLDER'))
	{
		header('Content-Type: text/xml; charset=utf-8');
		echo '<?xml version="1.0"?>';
		echo '<atomtask>';
		echo '<request>error.request.invalid</request>';
		echo '</atomtask>';
		return;
	}	

	// Include functions
	include_once(ROOT_FOLDER.'includes/user_func.php');
	include_once(ROOT_FOLDER.'db/connect_db.php');
	include_once(ROOT_FOLDER.'includes/auth_func.php');

	// Not enough information
	if (!isset($_POST['username']) || !isset($_POST['password']))
	{
		XML::write_element('result', 'error.user.login.invalid_input');
		return;
	}

	// Check valid information
	$username = trim(Text::standardize($_POST['username']));
	$password = trim(Text::standardize($_POST['password']));
	if (!User::is_valid_username($username) || !User::is_valid_password($password))
	{
		XML::write_element('result', 'error.user.login.invalid_input');
		return;
	}

	// Get user information
	$user = new User();
	if (!$user->get_information($username))
	{
		XML::write_element('result', 'error.user.login.user_not_existing');
		return;
	}
	// Check password
	if (User::encode_password($user->user_id, $password) != $user->password)
	{
		XML::write_element('result', 'error.user.login.fail');
		return;
	}

	// Login successfully
	$auth = new Authorize($user->user_id, "");
	if ($auth->new_token())
	{
		XML::write_element('result', 'success.user.login');
		XML::write_element('user_id', $auth->user_id);
		XML::write_element('token', $auth->token);
	}
	else
		XML::write_element('result', 'error.request.unknown');
?>